package com.media.appmedia.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.ClipboardManager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.WindowManager.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.ImageRequest;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.media.appmedia.R;
import com.media.appmedia.adapter.AttenListAdapter;
import com.media.appmedia.entity.AttenBeans;
import com.media.appmedia.lock.LockADWebView;
import com.media.appmedia.network.ProtocolConst;
import com.media.appmedia.network.ProtocolService;
import com.media.appmedia.util.MethodUtils;
import com.media.appmedia.util.PhoneInfoUtils;
import com.media.appmedia.util.SHA1Util;
import com.media.appmedia.util.ToastUtils;
import com.media.appmedia.util.VolleyHepler;
import com.umeng.socialize.bean.CallbackConfig.ICallbackListener;
import com.umeng.socialize.bean.RequestType;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.bean.SocializeEntity;
import com.umeng.socialize.bean.StatusCode;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.listener.SocializeListeners.SnsPostListener;
import com.umeng.socialize.media.QQShareContent;
import com.umeng.socialize.media.QZoneShareContent;
import com.umeng.socialize.media.RenrenShareContent;
import com.umeng.socialize.media.SinaShareContent;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.sso.EmailHandler;
import com.umeng.socialize.sso.QZoneSsoHandler;
import com.umeng.socialize.sso.RenrenSsoHandler;
import com.umeng.socialize.sso.SinaSsoHandler;
import com.umeng.socialize.sso.UMQQSsoHandler;
import com.umeng.socialize.sso.UMSsoHandler;
import com.umeng.socialize.weixin.controller.UMWXHandler;
import com.umeng.socialize.weixin.media.CircleShareContent;
import com.umeng.socialize.weixin.media.WeiXinShareContent;

public class Make_Money_Childer2 extends Fragment {
	@ViewInject(R.id.pull_to_refresh_listview)
	private ListView mListView;
	@ViewInject(R.id.hint)
	private TextView mTextView;
	private ArrayList<AttenBeans> beans;
	private ProgressDialog dialog;

	private View pop_view;
	private PopupWindow mPopupWindow;
	private PopupWindow mIsPopu;
	@ViewInject(R.id.count1_pop)
	private TextView textCount;
	@ViewInject(R.id.count3_pop)
	private TextView textAll;
	@ViewInject(R.id.atten_term)
	private TextView textDia;
	private int position;
	@ViewInject(R.id.edit_weix)
	private EditText editWeix;
	@ViewInject(R.id.edit_qq)
	private EditText editQq;
	private String weix;
	private String qq;

	private String shareContent = "我就是分享的内容";
//	private final String SHARE_TITLE = "升官发财";
	final UMSocialService mController = UMServiceFactory.getUMSocialService(
			"com.umeng.share", RequestType.SOCIAL);

	private int countShare = 0;

	Map<String, SHARE_MEDIA> mPlatformsMap = new HashMap<String, SHARE_MEDIA>();

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View mView = inflater.inflate(R.layout.makefragment2, null);
		ViewUtils.inject(this, mView);
		int a = MethodUtils.getShare(getActivity());
		if (a == 0) {
			// 弹窗注册关注信息
			// 并且进行数据存储
			initSharePopup();
		}

		mListView.setEmptyView(mTextView);
		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				if (beans != null && beans.size() > 0) {
					getAttenCount(beans.get(arg2).getAtten_list_name());
					textAll.setText("" + beans.get(arg2).getAtten_list_count());
					textDia.setText("分享并被好友查看 "
							+ beans.get(arg2).getAtten_list_count() + "次");
					position = arg2;
				}
			}
		});
		// 先适配，后更新
		getAttenResult();
		return mView;
	}

	private void getAttenResult() {
		ProtocolService.getAtten(PhoneInfoUtils.getIMEI(getActivity()),
				new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
						try {
							JSONObject obj = new JSONObject(arg0.result);
							if (obj.getInt("message") == 1) {
								beans = (ArrayList<AttenBeans>) JSONArray
										.parseArray(obj.getString("0"),
												AttenBeans.class);
								if (beans != null && beans.size() != 0) {
									AttenListAdapter adapter = new AttenListAdapter(
											beans, getActivity());
									mListView.setAdapter(adapter);
								}
								initPopup();
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}

					}

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						System.out.println("");
					}
				});
	}

	private void getAttenCount(String attenName) {
		dialog = new ProgressDialog(getActivity());
		dialog.setTitle("提示：");
		dialog.setMessage("拼命加载中。。。");
		dialog.show();

		ProtocolService.getAttenCount(PhoneInfoUtils.getIMEI(getActivity()),
				attenName, new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
						try {
							JSONObject obj = new JSONObject(arg0.result);
							if (obj.getInt("message") == 1) {
								int count = obj.getInt("atten_record_count");
								if (dialog != null) {
									dialog.dismiss();
								}
								textCount.setText("" + count);
								mPopupWindow.showAtLocation(pop_view,
										Gravity.CENTER, 0, 0);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						System.out.println("");

					}
				});
	}

	private void initPopup() {
		pop_view = LayoutInflater.from(getActivity()).inflate(
				R.layout.popu_atten_layout, null);
		mPopupWindow = new PopupWindow(pop_view, LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT);
//		mPopupWindow.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
		mPopupWindow.setFocusable(true);
		mPopupWindow.setOutsideTouchable(false);
		ViewUtils.inject(this, pop_view);
	}

	/*
	 * 初始化实例化第一次进入分享pop弹窗
	 */
	private void initSharePopup() {
		pop_view = LayoutInflater.from(getActivity()).inflate(
				R.layout.popu_share_layout, null);
		mIsPopu = new PopupWindow(pop_view, LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT);
//		mIsPopu.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
		// mIsPopu.setBackgroundDrawable(getResources().getDrawable(R.drawable.));
		mIsPopu.setFocusable(true);
		mIsPopu.setOutsideTouchable(false);
		mIsPopu.setAnimationStyle(R.style.anim_menu_popup);
		ViewUtils.inject(this, pop_view);
		mIsPopu.showAtLocation(pop_view, Gravity.CENTER, 0, 100);
	}

	@OnClick({ R.id.atten_pop, R.id.see_pop, R.id.close_pop,
			R.id.close_share_pop, R.id.sub_pop })
	public void setToLisetent(View view) {
		switch (view.getId()) {
		case R.id.atten_pop:
			// 打开分享界面
			loadData(beans.get(position).getAtten_list_photo(),
					beans.get(position).getAtten_list_type());
			break;
		case R.id.see_pop:
			// 弹窗中的预览按钮 打开网页
			Intent intent = new Intent(getActivity(), LockADWebView.class);
			intent.putExtra("url", beans.get(position).getAtten_list_url());
			startActivity(intent);
			break;
		case R.id.close_pop:
			if (mPopupWindow != null) {
				mPopupWindow.dismiss();
			}
			break;
		case R.id.close_share_pop:
			weix = editWeix.getText().toString().trim();
			qq = editQq.getText().toString().trim();
			if (!MethodUtils.isEmpty(weix) && !MethodUtils.isEmpty(qq)) {
				subQQ(weix, qq, false);
			}
			if (mIsPopu != null) {
				mIsPopu.dismiss();
			}
			break;
		case R.id.sub_pop:
			weix = editWeix.getText().toString().trim();
			qq = editQq.getText().toString().trim();
			if (MethodUtils.isEmpty(weix) || MethodUtils.isEmpty(qq)) {
				ToastUtils.show(getActivity(), "请输入完整的微信号和qq账号!");
				return;
			}
			if (mIsPopu != null) {
				mIsPopu.dismiss();
			}
			subQQ(weix, qq, true);
			break;
		default:
			break;
		}
	}

	private void initSocialSDK(Bitmap bitmaps, String shareContent,
			String title, String urlQQ, String urlQZ, String urlWx,
			String urlWxp, String urlRen, String urlTen, String urlXin,
			String urlYou) {
		mController.setShareContent(shareContent);
		// 图片分享内容
		mController.setShareMedia(new UMImage(getActivity(), bitmaps));
		// 设置新浪SSO handler
		mController.getConfig().setSsoHandler(new SinaSsoHandler());
		// 添加QQ空间平台 OK
		QZoneSsoHandler qzoneHandler = new QZoneSsoHandler(getActivity(),
				"1103456443", "lL5f5QHiGZn67ji8");
		qzoneHandler.addToSocialSDK();
		// 添加QQ平台 OK
		UMQQSsoHandler qqHandler = new UMQQSsoHandler(getActivity(),
				"1103456443", "lL5f5QHiGZn67ji8");
		qqHandler.addToSocialSDK();
		// // 微信平台
		String appID = "wx05f3d08ee1c4a3a0";
		String appSecret = "09470be5f3cbfc4113320a6360a85807";
		// // 添加微信平台
		UMWXHandler wxHandler = new UMWXHandler(getActivity(), appID, appSecret);
		wxHandler.addToSocialSDK();
		// 添加微信朋友圈
		UMWXHandler wxCircleHandler = new UMWXHandler(getActivity(), appID,
				appSecret);
		wxCircleHandler.setToCircle(true);
		wxCircleHandler.addToSocialSDK();
		// 人人网
		RenrenSsoHandler renrenSsoHandler = new RenrenSsoHandler(getActivity(),
				"273006", "20c2e3559525477ba47c1ad50bcc1cf1",
				"2360e8dafdad434780c8a08516d32adb");
		mController.getConfig().setSsoHandler(renrenSsoHandler);
		// 人人网分享内容
		RenrenShareContent renrenShareContent = new RenrenShareContent();
		renrenShareContent.setShareContent(shareContent);
		renrenShareContent.setShareImage(new UMImage(getActivity(), bitmaps));
		renrenShareContent.setTargetUrl(urlRen);
		mController.setAppWebSite(SHARE_MEDIA.RENREN, "http://www.sgfc88.com/");
		renrenSsoHandler.addToSocialSDK();
		mController.setShareMedia(renrenShareContent);
		// 添加email
		EmailHandler emailHandler = new EmailHandler();
		emailHandler.setTargetUrl(urlYou);
		emailHandler.addToSocialSDK();

		// 设置微信好友分享内容
		WeiXinShareContent weixinContent = new WeiXinShareContent();
		// 设置分享文字
		weixinContent.setShareContent(shareContent);
		// 设置title
		weixinContent.setTitle("升官发财");
		// 设置分享内容跳转URL
		weixinContent.setTargetUrl(urlWx);
		// 设置分享图片
		weixinContent.setShareImage(new UMImage(getActivity(), bitmaps));
		mController.setShareMedia(weixinContent);

		// 设置微信朋友圈分享内容
		CircleShareContent circleMedia = new CircleShareContent();
		circleMedia.setShareContent(shareContent);
		// 设置朋友圈title
		circleMedia.setTargetUrl(urlWxp);
		circleMedia.setTitle("升官发财\n" + shareContent);
		circleMedia.setShareImage(new UMImage(getActivity(), bitmaps));
		mController.setShareMedia(circleMedia);

		// 设置QQ空间分享内容
		QZoneShareContent qzone = new QZoneShareContent();
		qzone.setShareContent(shareContent);
		qzone.setTargetUrl(urlQZ);
		qzone.setTitle(title);
		qzone.setShareImage(new UMImage(getActivity(), bitmaps));
		// qzone.setShareImage(urlImage);
		mController.setShareMedia(qzone);

		// 设置QQ分享内容
		QQShareContent qqShareContent = new QQShareContent();
		// 设置分享文字
		qqShareContent.setShareContent(shareContent);
		// 设置分享title
		qqShareContent.setTitle(title);
		// 设置分享图片
		qqShareContent.setShareImage(new UMImage(getActivity(), bitmaps));
		// 设置点击分享内容的跳转链接
		qqShareContent.setTargetUrl(urlQQ);
		mController.setShareMedia(qqShareContent);
		// 设置新浪微博分享内容
		SinaShareContent sinaContent = new SinaShareContent();
		sinaContent.setShareContent(shareContent);
		sinaContent.setTitle(title);
		sinaContent.setTargetUrl(urlXin);
		sinaContent.setShareImage(new UMImage(getActivity(), bitmaps));
		mController.setShareMedia(sinaContent);
		countShare = 1;
		// mController.getConfig().registerListener(new SnsPostListener() {
		//
		// @Override
		// public void onStart() {
		// }
		//
		// @Override
		// public void onComplete(SHARE_MEDIA platform, int stCode,
		// SocializeEntity entity) {
		// String type = "";
		// if (platform == SHARE_MEDIA.QQ) {
		// type = "QQ";
		// } else if (platform == SHARE_MEDIA.RENREN) {
		// type = "人人网";
		// } else if (platform == SHARE_MEDIA.QZONE) {
		// type = "QQ空间";
		// } else if (platform == SHARE_MEDIA.EMAIL) {
		// type = "邮件";
		// } else if (platform == SHARE_MEDIA.TENCENT) {
		// type = "腾讯微博";
		// } else if (platform == SHARE_MEDIA.SINA) {
		// type = "新浪微博";
		// } else if (platform == SHARE_MEDIA.WEIXIN) {
		// type = "微信好友";
		// } else if (platform == SHARE_MEDIA.WEIXIN_CIRCLE) {
		// type = "微信朋友圈";
		// }
		// System.out.println("");
		// if (countShare == 1) {
		// ProtocolService.shareCount(PhoneInfoUtils
		// .getIMEI(getActivity()), beans.get(position)
		// .getAtten_list_name(), beans.get(position)
		// .getAtten_list_url(), type,
		// new RequestCallBack<String>() {
		//
		// @Override
		// public void onSuccess(ResponseInfo<String> arg0) {
		// ToastUtils
		// .show(getActivity(),
		// "---share success---"
		// + arg0.result);
		// }
		//
		// @Override
		// public void onFailure(HttpException arg0,
		// String arg1) {
		//
		// }
		// });
		// }
		// }
		// });
		//
	}

	/**
	 * 
	 * 方法说明：下载bitmap,并实例化分享平台和添加
	 * 
	 * @param url
	 */
	private void loadData(String url, final String shareString) {

		ImageRequest requests = new ImageRequest(url, new Listener<Bitmap>() {

			@Override
			public void onResponse(Bitmap response) {

				initSocialSDK(response,
						beans.get(position).getAtten_list_content(),
						beans.get(position).getAtten_list_title(),
						creatUrl("24"), creatUrl("6"), creatUrl("22"),
						creatUrl("23"), creatUrl("7"), creatUrl("2"),
						creatUrl("1"), creatUrl("18"));
				// 分享平台的添加显示
				mController.getConfig().setPlatforms(getShareMed(shareString));
				mController.openShare(getActivity(), false);
			}
		}, 0, 0, Config.ARGB_8888, null);
		requests.setTag(this);
		VolleyHepler.getInstance().addRequest(requests);
	}

	/**
	 * 
	 * 方法说明：创建对应的分享url 根据传入的type
	 * 
	 * @param type
	 * @return
	 */
	private String creatUrl(String type) {
		String urlencype = ProtocolConst.SHARE_1
				+ PhoneInfoUtils.getIMEI(getActivity()) + ProtocolConst.SHARE_2
				+ beans.get(position).getAtten_list_id()
				+ ProtocolConst.SHARE_5
				+ beans.get(position).getAtten_list_money()
				+ ProtocolConst.SHARE_4 + type;
		String url = urlencype + ProtocolConst.SHARE_7
				+ SHA1Util.hex_sha1(urlencype + ProtocolConst.SHARE_6)+ProtocolConst.SHARE_8;
		return url;

	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {

		super.onActivityResult(requestCode, resultCode, data);
		/** 使用SSO授权必须添加如下代码 */
		UMSsoHandler ssoHandler = mController.getConfig().getSsoHandler(
				requestCode);
		if (ssoHandler != null) {
			ssoHandler.authorizeCallBack(requestCode, resultCode, data);
		}

	}

	private void subQQ(String weix, String QQ, final boolean flage) {

		ProtocolService.subQQ(PhoneInfoUtils.getIMEI(getActivity()), weix, QQ,
				new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
						System.out.println("");
						try {
							JSONObject obj = new JSONObject(arg0.result);
							if (obj.getInt("message") == 1) {
								MethodUtils.setShare(getActivity(), 1);
								if (flage) {
									ToastUtils.show(getActivity(), "提交成功!");
								}
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}

					@Override
					public void onFailure(HttpException arg0, String arg1) {

					}
				});

	}

	/**
	 * 
	 * 方法说明：筛选分享平台
	 * 
	 * @param str
	 * @return
	 */
	private SHARE_MEDIA[] getShareMed(String str) {
		String[] strs = str.split(",");
		SHARE_MEDIA[] share = new SHARE_MEDIA[strs.length];
		for (int i = 0; i < strs.length; i++) {
			share[i] = getShare(strs[i]);
		}
		return share;
	}

	private SHARE_MEDIA getShare(String str) {
		SHARE_MEDIA share = null;
		if (str.equals("QQ")) {
			share = SHARE_MEDIA.QQ;
		} else if (str.equals("QQ空间")) {
			share = SHARE_MEDIA.QZONE;
		} else if (str.equals("人人网")) {
			share = SHARE_MEDIA.RENREN;
		} else if (str.equals("邮件")) {
			share = SHARE_MEDIA.EMAIL;
		} else if (str.equals("腾讯微博")) {
			share = SHARE_MEDIA.TENCENT;
		} else if (str.equals("新浪微博")) {
			share = SHARE_MEDIA.SINA;
		} else if (str.equals("微信好友")) {
			share = SHARE_MEDIA.WEIXIN;
		} else if (str.equals("微信朋友圈")) {
			share = SHARE_MEDIA.WEIXIN_CIRCLE;
		}

		return share;
	}

}
